<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800 mb-2">
        课程调整审批记录
      </h2>
      <p class="text-gray-500">
        查看所有课程调整申请的审批记录及状态
      </p>
    </div>

    <!-- 筛选区域 -->
    <el-card shadow="hover" class="mb-6 transition-all duration-300">
      <div class="filter-container p-4 bg-gray-50 rounded-lg">
        <el-row :gutter="20">
          <el-col :span="8" :xs="24">
            <el-select
                v-model="filterStatus"
                placeholder="审批状态"
                clearable
                @change="handleFilterChange"
                class="w-full"
            >
              <el-option label="全部状态" value=""></el-option>
              <el-option label="待审批" value="0"></el-option>
              <el-option label="已通过" value="1"></el-option>
              <el-option label="已拒绝" value="2"></el-option>
            </el-select>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-select
                v-model="filterType"
                placeholder="调整类型"
                clearable
                @change="handleFilterChange"
                class="w-full"
            >
              <el-option label="全部类型" value=""></el-option>
              <!-- 字典使用方式保持若依规范 -->
              <el-option
                  v-for="dict in reasons_adjusting_course"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-input
                placeholder="搜索课程名称..."
                prefix-icon="el-icon-search"
                v-model="searchKeyword"
                @input="handleSearch"
                class="w-full"
            ></el-input>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 审批记录表格 -->
    <el-card shadow="hover" class="transition-all duration-300">
      <el-table
          :data="currentPageRecords"
          border
          stripe
          :header-cell-style="{ background: '#f5f7fa' }"
          v-loading="loading"
          element-loading-text="加载审批记录中..."
          class="mb-4"
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="courseName" label="课程名称" min-width="180"></el-table-column>
        <el-table-column label="调整原因" min-width="120">
          <template #default="scope">
            {{ getAdjustReasonText(scope.row.adjustmentReason) }}
          </template>
        </el-table-column>
        <el-table-column label="调整范围" min-width="120">
          <template #default="scope">
            <el-tag type="info" size="small">
              {{ getAdjustmentRangeText(scope.row.adjustmentRange) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="原上课时间" min-width="180">
          <template #default="scope">
            <div>
              <p>{{ getWeekDay(scope.row.originalWeekDay) }}</p>
              <p class="text-sm text-gray-500">{{ scope.row.originalStartTime }}-{{ scope.row.originalEndTime }}</p>
              <p class="text-xs text-gray-400">第{{ scope.row.originalStartWeek }}-{{ scope.row.originalEndWeek }}周</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="调整后时间" min-width="180">
          <template #default="scope">
            <div v-if="scope.row.newWeekDay">
              <p>{{ getWeekDay(scope.row.newWeekDay) }}</p>
              <p class="text-sm text-gray-500">{{ scope.row.newStartTime }}-{{ scope.row.newEndTime }}</p>
              <p class="text-xs text-gray-400">第{{ scope.row.newStartWeek }}-{{ scope.row.newEndWeek }}周</p>
            </div>
            <div v-else class="text-gray-400">无</div>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" prop="createdAt" min-width="140">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="审批状态" min-width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.approvalStatus)" size="small">
              {{ getApprovalStatusText(scope.row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120">
          <template #default="scope">
            <el-button
                type="text"
                text-color="#165DFF"
                @click="openApprovalDialog(scope.row)"
                class="hover:text-primary/80 transition-colors"
                :disabled="scope.row.approvalStatus !== '0'"
            >
              审批申请
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 无数据状态 -->
      <div v-if="!loading && allRecords.length === 0" class="text-center py-10">
        <el-empty description="暂无课程调整审批记录"></el-empty>
      </div>

      <!-- 分页 -->
      <div v-if="allRecords.length > 0" class="flex justify-between items-center mt-4">
        <div class="text-sm text-gray-500">
          共 {{ allRecords.length }} 条记录，当前显示第 {{ (currentPage-1)*pageSize + 1 }}-{{ Math.min(currentPage*pageSize, allRecords.length) }} 条
        </div>
        <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="allRecords.length"
            layout="prev, pager, next, jumper, sizes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 审批弹窗（原安排+调整后安排各占一半） -->
    <el-dialog
        v-model="approvalDialogVisible"
        title="课程调整审批"
        width="90%"
        max-width="1200px"
        max-height="85vh"
        destroy-on-close
        :before-close="handleDialogClose"
        append-to-body
        scrollbar-always-on
    >
      <!-- 弹窗滚动容器 -->
      <div class="approval-detail overflow-y-auto" style="max-height: calc(85vh - 130px); padding-right: 8px;">
        <div v-if="currentApprovalRecord">
          <!-- 基础信息区域 - 若依风格 -->
          <div class="mb-5">
            <h4 class="font-semibold text-gray-800 mb-3 text-lg flex items-center">
              <i class="el-icon-info mr-2 text-primary"></i>申请基础信息
            </h4>
            <el-row :gutter="24" class="text-sm">
              <el-col :span="12" :sm="6" class="mb-2">
                <label class="text-gray-500 block mb-1 text-xs">课程名称</label>
                <p class="font-medium text-ellipsis overflow-hidden whitespace-nowrap">{{ currentApprovalRecord.originalClassName || '未知课程' }}</p>
              </el-col>
              <el-col :span="12" :sm="6" class="mb-2">
                <label class="text-gray-500 block mb-1 text-xs">调整类型</label>
                <p class="font-medium">{{ getAdjustReasonText(currentApprovalRecord.adjustmentReason) }}</p>
              </el-col>
              <el-col :span="12" :sm="6" class="mb-2">
                <label class="text-gray-500 block mb-1 text-xs">调整范围</label>
                <p class="font-medium">{{ getAdjustmentRangeText(currentApprovalRecord.adjustmentRange) }}</p>
              </el-col>
              <el-col :span="12" :sm="6" class="mb-2">
                <label class="text-gray-500 block mb-1 text-xs">申请时间</label>
                <p class="font-medium">{{ formatDate(currentApprovalRecord.createdAt) }}</p>
              </el-col>
            </el-row>
          </div>

          <!-- 时间调整对比区域（核心布局修改） -->
          <div class="mb-5">
            <h4 class="font-semibold text-gray-800 mb-3 text-lg flex items-center">
              <i class="el-icon-calendar mr-2 text-primary"></i>时间调整对比
            </h4>
            <div class="grid grid-cols-2 gap-4" style="grid-template-columns: 1fr 1fr;">
              <!-- 原安排（左侧，合并为一行） -->
              <div class="border rounded-lg p-4 bg-gray-50 shadow-sm hover:shadow transition-shadow w-full h-full">
                <h5 class="text-gray-700 font-medium mb-3 flex items-center">
                  <span class="inline-block w-2 h-2 bg-blue-500 rounded-full mr-2"></span>
                  原安排
                </h5>
                <div class="space-y-1 text-sm">
                  <p class="font-medium">
                    {{ getWeekDay(currentApprovalRecord.originalWeekDay) }} {{ currentApprovalRecord.originalStartTime }}-{{ currentApprovalRecord.originalEndTime }}
                    <span class="mx-1">|</span>
                    第{{ currentApprovalRecord.originalStartWeek }}-{{ currentApprovalRecord.originalEndWeek }}周
                    <span class="mx-1">|</span>
                    {{ currentApprovalRecord.originalClassroom || '未知教室' }}
                  </p>
                </div>
              </div>
              <!-- 调整后安排（右侧，合并为一行，清理冗余结构） -->
              <div class="border rounded-lg p-4 bg-gray-50 shadow-sm hover:shadow transition-shadow w-full h-full">
                <h5 class="text-gray-700 font-medium mb-3 flex items-center">
                  <span class="inline-block w-2 h-2 bg-green-500 rounded-full mr-2"></span>
                  调整后安排
                </h5>
                <div class="space-y-1 text-sm">
                  <p class="font-medium" v-if="currentApprovalRecord.newWeekDay">
                    {{ getWeekDay(currentApprovalRecord.newWeekDay) }} {{ currentApprovalRecord.newStartTime }}-{{ currentApprovalRecord.newEndTime }}
                    <span class="mx-1">|</span>
                    第{{ currentApprovalRecord.newStartWeek }}-{{ currentApprovalRecord.newEndWeek }}周（{{ getWeekTypeText(currentApprovalRecord.newWeekType) }}）
                    <span class="mx-1">|</span>
                    {{ currentApprovalRecord.newClassroom || '未知教室' }}
                  </p>
                  <p class="text-gray-400" v-else>无</p>
                </div>
              </div>
            </div>
          </div>

          <!-- 申请说明区域 -->
          <div class="mb-5">
            <h4 class="font-semibold text-gray-800 mb-3 text-lg flex items-center">
              <i class="el-icon-message mr-2 text-primary"></i>申请说明
            </h4>
            <div class="border rounded-lg p-3 min-h-[60px] bg-gray-50 shadow-sm">
              <p class="text-sm whitespace-pre-line">{{ currentApprovalRecord.adjustmentDescription || '无申请说明' }}</p>
            </div>
          </div>

          <!-- 审批状态区域 -->
          <div class="mb-5">
            <h4 class="font-semibold text-gray-800 mb-3 text-lg flex items-center">
              <i class="el-icon-check-circle mr-2 text-primary"></i>审批状态
            </h4>
            <div class="flex items-center flex-wrap gap-2 text-sm">
              <el-tag :type="getStatusTagType(currentApprovalRecord.approvalStatus)" size="small" class="px-3">
                {{ getApprovalStatusText(currentApprovalRecord.approvalStatus) }}
              </el-tag>
              <div v-if="currentApprovalRecord.approvedAt" class="text-gray-600">
                审批时间：{{ formatDate(currentApprovalRecord.approvedAt) }}
              </div>
              <div v-if="currentApprovalRecord.approverName" class="text-gray-600 ml-3">
                审批人：{{ currentApprovalRecord.approverName }}
              </div>
            </div>
          </div>

          <!-- 审批操作区域（仅待审批状态显示） -->
          <div v-if="currentApprovalRecord.approvalStatus === '0'" class="mt-6 border-t pt-4">
            <h4 class="font-semibold text-gray-800 mb-3 text-lg flex items-center">
              <i class="el-icon-edit mr-2 text-primary"></i>审批操作
            </h4>
            <el-form :model="approvalForm" :rules="approvalRules" ref="approvalFormRef" label-width="80px" size="small">
              <el-form-item label="审批意见" prop="approvalOpinion">
                <el-input
                    v-model="approvalForm.approvalOpinion"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入审批意见（可选）"
                    max-length="500"
                    show-word-limit
                    class="resize-none"
                ></el-input>
              </el-form-item>
              <div class="flex justify-end gap-2 mt-2">
                <el-button type="default" size="small" @click="approvalDialogVisible = false">取消</el-button>
                <el-button type="danger" size="small" @click="handleReject">拒绝</el-button>
                <el-button type="primary" size="small" @click="handleApprove">通过</el-button>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, getCurrentInstance, computed} from 'vue';
import {ElMessage, ElEmpty} from 'element-plus';
import {selectAdjustmentRecord} from "@/api/course/availability";
import {updateCourseAdjustmentRecord} from "@/api/trainingManagement/CourseAdjustmentRecord";
import {listsClassroom} from "@/api/classroom/classroom";
import {useRouter} from 'vue-router';
import useUserStore from '@/store/modules/user';

// 路由实例
const router = useRouter();

// 用户 store
const userStore = useUserStore();

// 核心状态管理（若依字典规范）
const {proxy} = getCurrentInstance();
const {reasons_adjusting_course} = proxy.useDict("reasons_adjusting_course");

// 页面状态
const allRecords = ref([]);
const filteredRecords = ref([]);
const loading = ref(false);
const approvalDialogVisible = ref(false);
const currentApprovalRecord = ref(null);
const approvalFormRef = ref(null);
const approvalForm = ref({approvalOpinion: ''});
const approvalRules = ref({
  approvalOpinion: [{max: 500, message: '审批意见不能超过500字', trigger: 'blur'}]
});
const classrooms = ref([]);
const filterStatus = ref('');
const filterType = ref('');
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);

// 计算属性 - 分页数据
const currentPageRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredRecords.value.slice(start, end);
});

// 工具方法 - 调整原因字典转换
const getAdjustReasonText = (reasonValue) => {
  if (!reasonValue && reasonValue !== 0) return '未知类型';
  const dictItem = reasons_adjusting_course.value?.find(
      dict => parseInt(dict.value) === parseInt(reasonValue)
  );
  return dictItem?.label || '未知类型';
};

// 工具方法 - 调整范围转换
const getAdjustmentRangeText = (range) => {
  const rangeValue = String(range || '').trim();
  const rangeMap = {
    '1': '临时调整',
    '2': '调整整个周期',
    'temporary': '临时调整',
    'entire': '调整整个周期'
  };
  return rangeMap[rangeValue] || `未知(${range})`;
};

// 工具方法 - 星期转换
const getWeekDay = (day) => {
  const weekdays = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  return weekdays[parseInt(day, 10)] || '未知';
};

// 工具方法 - 周类型转换（单周/双周/每周）
const getWeekTypeText = (weekType) => {
  const weekTypeMap = {'1': '每周', '2': '单周', '4': '双周'};
  return weekTypeMap[String(weekType)] || `未知(${weekType})`;
};

// 工具方法 - 审批状态文本转换
const getApprovalStatusText = (status) => {
  switch (status) {
    case '0':
      return '待审批';
    case '1':
      return '已通过';
    case '2':
      return '已拒绝';
    default:
      return `未知(${status})`;
  }
};

// 工具方法 - 审批状态标签类型转换
const getStatusTagType = (status) => {
  switch (status) {
    case '0':
      return 'info';
    case '1':
      return 'success';
    case '2':
      return 'danger';
    default:
      return 'warning';
  }
};

// 工具方法 - 日期格式化（若依标准）
const formatDate = (dateString) => {
  if (!dateString) return '';
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit'
  }).replace(/\//g, '-');
};

// 页面初始化加载数据
onMounted(async () => {
  // 获取当前用户信息（调试用）
  console.log('当前用户信息:', {
    name: userStore.name,
    nickName: userStore.nickName,
    roles: userStore.roles,
    userId: userStore.userId
  });

  await initData();
});

// 初始化数据逻辑
const initData = async () => {
  loading.value = true;
  try {
    // 并行请求教室列表和审批记录
    const [classroomResult, recordsResult] = await Promise.all([
      listsClassroom().catch(err => {
        console.error('加载教室列表失败:', err);
        return [];
      }),
      selectAdjustmentRecord().catch(err => {
        console.error('加载审批记录失败:', err);
        return [];
      })
    ]);

    // 处理教室数据（兼容若依接口返回格式）
    classrooms.value = Array.isArray(classroomResult)
        ? classroomResult
        : Array.isArray(classroomResult?.data)
            ? classroomResult.data
            : [];

    // 处理审批记录（兼容若依接口返回格式：支持直接数组、data字段、rows字段）
    let records = [];
    if (Array.isArray(recordsResult)) {
      records = recordsResult;
    } else if (Array.isArray(recordsResult?.data)) {
      records = recordsResult.data;
    } else if (Array.isArray(recordsResult?.rows)) {
      records = recordsResult.rows;
    }

    // 统一课程名称字段
    allRecords.value = records.map(record => ({
      ...record,
      courseName: record.originalClassName || record.courseName || '未知课程'
    }));

    // 初始化筛选
    applyFilters();
  } catch (error) {
    console.error('页面初始化失败:', error);
    ElMessage.error("页面加载失败，请刷新重试");
  } finally {
    loading.value = false;
  }
};

// 筛选逻辑（状态+类型+关键词）
const applyFilters = () => {
  let result = [...allRecords.value];

  // 审批状态筛选
  if (filterStatus.value) {
    result = result.filter(r => r.approvalStatus === filterStatus.value);
  }

  // 调整类型筛选（数字匹配）
  if (filterType.value) {
    const filterCode = Number(filterType.value);
    result = result.filter(r => Number(r.adjustmentReason) === filterCode);
  }

  // 关键词搜索（不区分大小写）
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(r =>
        (r.courseName?.toLowerCase().includes(keyword)) ||
        (r.adjustmentDescription?.toLowerCase().includes(keyword)) ||
        (getAdjustReasonText(r.adjustmentReason)?.toLowerCase().includes(keyword))
    );
  }

  filteredRecords.value = result;
  currentPage.value = 1; // 筛选后重置页码
};

// 搜索框输入触发筛选
const handleSearch = () => applyFilters();
// 筛选条件变更触发筛选
const handleFilterChange = () => applyFilters();
// 每页条数变更
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};
// 页码变更
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 打开审批弹窗
const openApprovalDialog = (record) => {
  currentApprovalRecord.value = {...record}; // 深拷贝避免原数据污染
  approvalForm.value = {approvalOpinion: ''}; // 重置表单
  approvalDialogVisible.value = true;
};

// 弹窗关闭钩子（清理验证+重置数据）
const handleDialogClose = () => {
  if (approvalFormRef.value) {
    approvalFormRef.value.clearValidate();
  }
  approvalForm.value = {approvalOpinion: ''};
  approvalDialogVisible.value = false;
};

// 审批通过
const handleApprove = async () => {
  await submitApproval('1', '通过');
};

// 审批拒绝
const handleReject = async () => {
  await submitApproval('2', '拒绝');
};

// 核心审批提交逻辑（使用 useUserStore 获取用户信息）
const submitApproval = async (status, statusText) => {
  // 表单验证（可选字段也触发验证，确保无格式错误）
  if (approvalFormRef.value) {
    const valid = await approvalFormRef.value.validate();
    if (!valid) return;
  }

  // 使用 useUserStore 获取用户信息
  const approverId = userStore.userId || userStore.id;
  const approverName = userStore.nickName || userStore.name;

  // 校验用户信息（必须登录且有用户ID/姓名）
  if (!approverId || !approverName) {
    ElMessage.error("获取用户信息失败，请重新登录后重试");
    return;
  }

  try {
    // 调用后端更新接口（参数完全匹配实体类）
    await updateCourseAdjustmentRecord({
      id: currentApprovalRecord.value.id, // 审批记录主键（必传）
      approvalStatus: status, // 审批状态（1=通过/2=拒绝）
      approvalOpinion: approvalForm.value.approvalOpinion || `已${statusText}审批`, // 默认意见
      approverId: approverId, // 审批人ID（当前登录用户）
      approverName: approverName, // 审批人姓名（当前登录用户）
      approvedAt: new Date().toISOString() // 审批时间（ISO标准格式）
    });

    // 提交成功反馈
    ElMessage.success(`审批${statusText}成功`);
    approvalDialogVisible.value = false;
    await initData(); // 刷新页面数据
  } catch (error) {
    console.error(`审批${statusText}失败:`, error);
    ElMessage.error(`审批${statusText}失败: ${error.message || '未知错误'}`);
  }
};
</script>

<style scoped lang="scss">
// 若依标准布局样式
.app-container {
  padding: 20px;
  margin: 0 auto;
  max-width: 1920px;
}

.page-header {
  margin-bottom: 24px;
}

.filter-container {
  margin-bottom: 16px;
}

/* 审批弹窗样式 */
.approval-detail {
  padding: 5px 0;
}

// 网格布局（强制两列等宽）
.approval-detail .grid {
  display: grid !important;
  width: 100% !important;
}

.approval-detail .grid-cols-2 {
  grid-template-columns: 1fr 1fr !important;
  gap: 1rem !important;
}

// 卡片样式优化
.approval-detail .border {
  border: 1px solid #e5e7eb;
}

.approval-detail .rounded-lg {
  border-radius: 0.5rem;
}

.approval-detail .p-4 {
  padding: 1rem;
}

.approval-detail .bg-gray-50 {
  background-color: #f9fafb;
}

.approval-detail .shadow-sm {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.approval-detail .hover\:shadow:hover {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

/* 表格样式优化 */
::v-deep .el-card {
  transition: all 0.3s ease;
  width: 100%;
}

::v-deep .el-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

::v-deep .el-table {
  width: 100% !important;
  transition: all 0.3s ease;
}

::v-deep .el-table__row:hover {
  background-color: #f9fafb;
}

/* 弹窗滚动条优化 */
::v-deep .approval-detail::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::v-deep .approval-detail::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::v-deep .approval-detail::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::v-deep .approval-detail::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 弹窗组件样式（若依统一风格） */
::v-deep .el-dialog {
  max-width: 1200px !important;
  min-width: 800px;
}

::v-deep .el-dialog__header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
}

::v-deep .el-dialog__body {
  padding: 16px 20px 10px;
  overflow: hidden;
}

/* 响应式适配（移动端单列布局） */
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
    overflow-x: auto;
  }

  ::v-deep .el-col {
    margin-bottom: 10px;
  }

  // 移动端改为单列
  .approval-detail .grid-cols-2 {
    grid-template-columns: 1fr !important;
  }

  ::v-deep .el-dialog {
    width: 95% !important;
    max-height: 80vh !important;
    min-width: auto;
  }
}

/* 组件尺寸统一 */
::v-deep .el-button--small {
  padding: 6px 12px;
}

::v-deep .el-form-item--small .el-form-item__label {
  font-size: 13px;
}

::v-deep .el-textarea--small {
  padding: 8px 12px;
  font-size: 13px;
}

// 文本间距优化
.approval-detail .space-y-1 > * + * {
  margin-top: 0.25rem;
}

.approval-detail .mx-1 {
  margin: 0 0.25rem;
}
</style>